#include "gethostnameipinfo.h"
#include <QMessageBox>

GetHostNameIPInfo::GetHostNameIPInfo(QWidget *parent)
        : QDialog(parent)
{
    setWindowTitle("获取本地主机名称和IP及所有信息");
    resize(500, 150);

    QLabel *label_hostname = new QLabel("主机名称：");
    QLabel *label_hostip = new QLabel("主机IP地址：");

    lineEdit_hostname = new QLineEdit(this);
    lineEdit_hostip = new QLineEdit(this);

    button_GetHostNameIP = new QPushButton("获取主机名称和IP地址", this);
    button_GetHostInfo = new QPushButton("获取主机所有信息", this);

    // 左侧布局：标签
    QVBoxLayout *labelLayout = new QVBoxLayout;
    labelLayout->addWidget(label_hostname);
    labelLayout->addWidget(label_hostip);

    // 中间布局：输入框
    QVBoxLayout *lineEditLayout = new QVBoxLayout;
    lineEditLayout->addWidget(lineEdit_hostname);
    lineEditLayout->addWidget(lineEdit_hostip);

    // 右侧布局：按钮
    QVBoxLayout *buttonLayout = new QVBoxLayout;
    buttonLayout->addWidget(button_GetHostNameIP);
    buttonLayout->addWidget(button_GetHostInfo);

    // 合并成主行布局
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->addLayout(labelLayout);
    mainLayout->addLayout(lineEditLayout);
    mainLayout->addLayout(buttonLayout);

    // 信号槽连接
    connect(button_GetHostNameIP, &QPushButton::clicked, this, &GetHostNameIPInfo::onGetHostNameIPClicked);
    connect(button_GetHostInfo, &QPushButton::clicked, this, &GetHostNameIPInfo::onGetHostInfoClicked);
}

GetHostNameIPInfo::~GetHostNameIPInfo() {}

void GetHostNameIPInfo::GetHostNameAndIpAddress()
{
    QString localHostName = QHostInfo::localHostName();
    lineEdit_hostname->setText(localHostName);

    QHostInfo hostInfo = QHostInfo::fromName(localHostName);
    QString ipAddress;

    for (const QHostAddress &address : hostInfo.addresses())
    {
        if (address.protocol() == QAbstractSocket::IPv4Protocol)
        {
            ipAddress = address.toString();
            break;
        }
    }

    lineEdit_hostip->setText(ipAddress);
}

void GetHostNameIPInfo::onGetHostNameIPClicked()
{
    GetHostNameAndIpAddress();
}

void GetHostNameIPInfo::onGetHostInfoClicked()
{
    QString strTemp;
    QList<QNetworkInterface> netList = QNetworkInterface::allInterfaces();

    for (const QNetworkInterface &iface : netList)
    {
        strTemp += "设备名称：" + iface.name() + "\n";
        strTemp += "硬件地址：" + iface.hardwareAddress() + "\n";

        for (const QNetworkAddressEntry &entry : iface.addressEntries())
        {
            strTemp += "IP地址：" + entry.ip().toString() + "\n";
            strTemp += "子网掩码：" + entry.netmask().toString() + "\n";
            strTemp += "广播地址：" + entry.broadcast().toString() + "\n";
        }

        strTemp += "\n";
    }

    QMessageBox::information(this, "主机所有信息", strTemp, QMessageBox::Yes);
}
